﻿using System;
using System.Diagnostics;
using Hammock;
using Hammock.Authentication.OAuth;
using Newtonsoft.Json.Linq;
using WeiboPlus.Models;
using WeiboPlus.Service;

namespace WeiboPlus.Renren
{
    public class RenrenOAuthService : OAuthServiceBase
    {
        public RenrenOAuthService()
        {
            Provider = RenRenSNSProviderFactory.Instance.GetProvider();
        }

        protected override Hammock.Authentication.IWebCredentials CreateCredentials(OAuthType type)
        {
            return base.CreateCredentials(type);
        }

        public override void AccessToken(Action<SNSAccount,SNSResult> action)
        {
            var request = new RestRequest()
            {
                Path = Provider.AuthSettings.PATH_ACCESS_TOKEN  
            };

            request.AddParameter("grant_type", "authorization_code");
            request.AddParameter("code", Account.PIN);
            request.AddParameter("client_id", Provider.AuthSettings.CONSUMER_KEY);
            request.AddParameter("client_secret", Provider.AuthSettings.CONSUMER_KEY_SECRET);
            request.AddParameter("redirect_uri", Provider.AuthSettings.CALLBACK_URL);

            Execute((res) =>
            {
                Debug.WriteLine(res.Content);

                JObject o = JObject.Parse(res.Content);
                string msg;
                if (ValidateResponse(res, out msg)==0)
                {
                    //TO-DO
                    if (action != null)
                    {
                        action(Account, new SNSResult() { IsSuccess = false, Message = msg });
                    }
                }
                string access_token = (string)o.SelectToken("access_token");
                int expires_in = (int)o.SelectToken("expires_in");
                string refresh_token = (string)o.SelectToken("refresh_token");
                string scope = (string)o.SelectToken("scope");

                Account.AccessToken = access_token;
                Account.ExpiresIn = expires_in;
                Account.RefreshToken = refresh_token;
                Account.Scope = scope;
                Account.IsBind = true;

                if (action != null)
                {
                    action(Account, new SNSResult() { IsSuccess = true, Message = msg });
                }
            }, request);
            //base.AccessToken(action);
        }

        public override void RequestToken(Action<SNSAccount,SNSResult> action)
        {
            string authUrl = string.Format("{0}{1}?client_id={2}&response_type=code&redirect_uri={3}&scope=read_user_status,read_user_feed,status_update,read_user_photo,publish_feed,read_user_share,read_user_comment,photo_upload,publish_comment,publish_share&display=touch", Provider.AuthSettings.CLIENT, Provider.AuthSettings.PATH_AUTHORIZE, Provider.AuthSettings.CONSUMER_KEY, Provider.AuthSettings.CALLBACK_URL);
            Account.AuthorizeURL = authUrl;
            action(Account, new SNSResult() { IsSuccess=true,Message = "Require Request Token Success"});
            //base.RequestToken(action);
        }

        public override void AccessTokenRefresh(Action<SNSAccount,SNSResult> action)
        {
            var request = new RestRequest()
            {
                Path = Provider.AuthSettings.PATH_ACCESS_TOKEN  
            };

            request.AddParameter("grant_type", "refresh_token");
            request.AddParameter("refresh_token", Account.RefreshToken);
            request.AddParameter("client_id", Provider.AuthSettings.CONSUMER_KEY);
            request.AddParameter("client_secret", Provider.AuthSettings.CONSUMER_KEY_SECRET);
            request.AddParameter("redirect_uri", Provider.AuthSettings.CALLBACK_URL);

            Execute((res) =>
            {
                Debug.WriteLine(res.Content);

                JObject o = JObject.Parse(res.Content);
                string msg;
                if(ValidateResponse(res,out msg)!=0)
                {
                    //TO-DO
                    if (action != null)
                    {
                        action(Account, new SNSResult() { IsSuccess = false, Message = msg });
                    }
                }
                string access_token = (string)o.SelectToken("access_token");
                int expires_in = (int)o.SelectToken("expires_in");
                string refresh_token = (string)o.SelectToken("refresh_token");
                string scope = (string)o.SelectToken("scope");

                Account.AccessToken = access_token;
                Account.ExpiresIn = expires_in;
                Account.RefreshToken = refresh_token;
                Account.Scope = scope;
                Account.IsBind = true;

                if (action != null)
                {
                    action(Account, new SNSResult() { IsSuccess = true, Message = msg });
                }
                
            }, request);
            //base.AccessToken(action);
        }

    }
}
